#!/usr/bin/env python3
"""
日志查看工具
用于查看和分析应用日志
"""
import os
import sys
import argparse
from datetime import datetime, timedelta
from pathlib import Path

def tail_file(file_path, lines=50):
    """查看文件最后几行"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            all_lines = f.readlines()
            return all_lines[-lines:]
    except FileNotFoundError:
        print(f"文件不存在: {file_path}")
        return []
    except Exception as e:
        print(f"读取文件失败: {e}")
        return []

def grep_file(file_path, pattern, case_sensitive=False):
    """在文件中搜索模式"""
    try:
        import re
        flags = 0 if case_sensitive else re.IGNORECASE
        pattern_re = re.compile(pattern, flags)
        
        matches = []
        with open(file_path, 'r', encoding='utf-8') as f:
            for line_num, line in enumerate(f, 1):
                if pattern_re.search(line):
                    matches.append((line_num, line.strip()))
        
        return matches
    except FileNotFoundError:
        print(f"文件不存在: {file_path}")
        return []
    except Exception as e:
        print(f"搜索文件失败: {e}")
        return []

def get_log_stats(file_path):
    """获取日志统计信息"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            lines = f.readlines()
        
        total_lines = len(lines)
        error_count = sum(1 for line in lines if 'ERROR' in line)
        warning_count = sum(1 for line in lines if 'WARNING' in line)
        info_count = sum(1 for line in lines if 'INFO' in line)
        
        return {
            'total_lines': total_lines,
            'error_count': error_count,
            'warning_count': warning_count,
            'info_count': info_count
        }
    except FileNotFoundError:
        return None
    except Exception as e:
        print(f"获取日志统计失败: {e}")
        return None

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='日志查看工具')
    parser.add_argument('--file', '-f', default='app.log', help='日志文件路径')
    parser.add_argument('--lines', '-n', type=int, default=50, help='显示行数')
    parser.add_argument('--grep', '-g', help='搜索模式')
    parser.add_argument('--case-sensitive', '-i', action='store_true', help='区分大小写')
    parser.add_argument('--stats', '-s', action='store_true', help='显示统计信息')
    parser.add_argument('--errors', '-e', action='store_true', help='只显示错误日志')
    parser.add_argument('--follow', '-F', action='store_true', help='实时跟踪日志')
    
    args = parser.parse_args()
    
    # 检查文件是否存在
    if not os.path.exists(args.file):
        print(f"日志文件不存在: {args.file}")
        print("可用的日志文件:")
        for log_file in ['app.log', 'error.log', 'access.log']:
            if os.path.exists(log_file):
                print(f"  - {log_file}")
        return
    
    # 显示统计信息
    if args.stats:
        stats = get_log_stats(args.file)
        if stats:
            print(f"📊 日志统计信息 - {args.file}")
            print("=" * 50)
            print(f"总行数: {stats['total_lines']}")
            print(f"错误数: {stats['error_count']}")
            print(f"警告数: {stats['warning_count']}")
            print(f"信息数: {stats['info_count']}")
            print()
    
    # 搜索模式
    if args.grep:
        print(f"🔍 搜索模式: {args.grep}")
        print("=" * 50)
        matches = grep_file(args.file, args.grep, args.case_sensitive)
        if matches:
            for line_num, line in matches:
                print(f"{line_num:6d}: {line}")
        else:
            print("未找到匹配项")
        return
    
    # 只显示错误日志
    if args.errors:
        print("🚨 错误日志")
        print("=" * 50)
        matches = grep_file(args.file, r'ERROR|CRITICAL|FATAL')
        if matches:
            for line_num, line in matches:
                print(f"{line_num:6d}: {line}")
        else:
            print("未找到错误日志")
        return
    
    # 实时跟踪
    if args.follow:
        print(f"👀 实时跟踪日志: {args.file}")
        print("按 Ctrl+C 停止")
        print("=" * 50)
        try:
            import time
            with open(args.file, 'r', encoding='utf-8') as f:
                # 移动到文件末尾
                f.seek(0, 2)
                while True:
                    line = f.readline()
                    if line:
                        print(line.strip())
                    else:
                        time.sleep(0.1)
        except KeyboardInterrupt:
            print("\n停止跟踪")
        return
    
    # 显示最后几行
    print(f"📄 日志文件: {args.file}")
    print("=" * 50)
    lines = tail_file(args.file, args.lines)
    for i, line in enumerate(lines, 1):
        print(f"{i:6d}: {line.strip()}")

if __name__ == "__main__":
    main()
